package com.scu.phototabuser.data.source.remote;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scu.phototabuser.Consts;
import com.scu.phototabuser.data.Taskable;
import com.scu.phototabuser.data.source.local.Token;
import com.scu.phototabuser.http.OkHttp3Methods;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by tianfei on 2017/5/14.
 */

public abstract class RefreshTokenTaskable extends Taskable<String> {


    private boolean isSucceed =false;


    @Override
    public boolean isSucceed() {
        return isSucceed;
    }

    @Override
    public void start(TASK_TYPE type) {
        doAsyc();
    }

    private void doAsyc(){
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {

                String json= OkHttp3Methods.PostRequestWithToken(Consts.RefreshTokenURL,null);

                Response<Token> res=new Gson().fromJson(json,
                        new TypeToken<Response<Token>>(){}.getType());

                if (res.getCode() ==200){
                    String token=res.getData().getToken();
                    e.onNext(token);
                }else {
                    e.onError(new RuntimeException(res.getMessage()));
                }
            }
        }).subscribeOn(Schedulers.io())
        .subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {}

            @Override
            public void onNext(@NonNull String s) {
                RefreshTokenTaskable.this.isSucceed=true;
                RefreshTokenTaskable.this.onSuccess(s);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                RefreshTokenTaskable.this.onFailed(-1,e.getMessage());
            }

            @Override
            public void onComplete() {}
        });

    }
}
